"use client"

import { useParams, useNavigate, Link } from "react-router-dom"
import { Button, Typography, Space, Breadcrumb, Spin, Empty, Row, Col, Modal, Card } from "antd"
import {
  ProjectOutlined,
  FileTextOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  CloudServerOutlined,
  ArrowLeftOutlined,
} from "@ant-design/icons"
import { useHosts } from "../contexts/HostsContext"
import HostsBlockCard from "../components/HostsBlockCard"

const { Title, Text } = Typography
const { confirm } = Modal

const ModuleDetail = () => {
  const { projectId, moduleId } = useParams<{ projectId: string; moduleId: string }>()
  const navigate = useNavigate()
  const { projects, modules, hostsBlocks, loading, deleteModule, deleteHostsBlock } = useHosts()

  if (!projectId || !moduleId) {
    navigate("/projects")
    return null
  }

  const project = projects.find((p) => p.id === projectId)
  const module = modules.find((m) => m.id === moduleId)
  const moduleHostsBlocks = hostsBlocks.filter((h) => h.moduleId === moduleId)

  if (loading) {
    return (
      <div style={{ textAlign: "center", padding: "40px 0" }}>
        <Spin size="large" />
      </div>
    )
  }

  if (!project || !module) {
    return (
      <div className="empty-container">
        <Empty description="项目或模块不存在或已被删除">
          <Button type="primary" onClick={() => navigate("/projects")}>
            返回项目列表
          </Button>
        </Empty>
      </div>
    )
  }

  const handleDeleteModule = () => {
    confirm({
      title: "确定要删除此模块吗?",
      icon: <ExclamationCircleOutlined />,
      content: `删除模块 "${module.name}" 将同时删除其下所有 Hosts 配置，此操作不可恢复。`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        deleteModule(module.id)
        navigate(`/projects/${projectId}`)
      },
    })
  }

  const handleDeleteHostsBlock = (id: string) => {
    deleteHostsBlock(id)
  }

  return (
    <div className="fade-in">
      <Breadcrumb className="breadcrumb mb-4">
        <Breadcrumb.Item>
          <Link to="/">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/projects">项目管理</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to={`/projects/${projectId}`}>{project.name}</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>{module.name}</Breadcrumb.Item>
      </Breadcrumb>

      <Card className="enhanced-card mb-6">
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "flex-start",
            flexWrap: "wrap",
            gap: "16px",
          }}
        >
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "16px" }}>
              <div
                style={{
                  width: "48px",
                  height: "48px",
                  borderRadius: "8px",
                  backgroundColor: "#8b5cf6",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "white",
                  fontSize: "24px",
                }}
              >
                <FileTextOutlined />
              </div>
              <div>
                <Title level={4} style={{ margin: 0 }}>
                  {module.name}
                </Title>
                <Space style={{ marginTop: "4px" }}>
                  <span className="badge badge-blue">
                    <ProjectOutlined style={{ marginRight: "4px" }} />
                    {project.name}
                  </span>
                  <Text type="secondary" style={{ fontSize: "13px" }}>
                    创建于 {new Date(module.createdAt).toLocaleDateString()}
                  </Text>
                </Space>
              </div>
            </div>
            <div style={{ marginTop: "12px", color: "var(--gray-700)" }}>{module.description || "暂无描述"}</div>
          </div>
          <Space>
            <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(`/projects/${projectId}`)}>
              返回项目
            </Button>
            <Button icon={<EditOutlined />}>编辑模块</Button>
            <Button icon={<DeleteOutlined />} danger onClick={handleDeleteModule}>
              删除模块
            </Button>
          </Space>
        </div>
      </Card>

      <Card
        className="enhanced-card"
        title={
          <div style={{ display: "flex", alignItems: "center" }}>
            <CloudServerOutlined style={{ marginRight: "8px" }} />
            <span>Hosts 配置列表</span>
          </div>
        }
      >
        {moduleHostsBlocks.length === 0 ? (
          <Empty description="暂无 Hosts 配置" />
        ) : (
          <Row gutter={[24, 24]}>
            {moduleHostsBlocks.map((block) => (
              <Col xs={24} sm={12} key={block.id}>
                <HostsBlockCard hostsBlock={block} onDelete={() => handleDeleteHostsBlock(block.id)} />
              </Col>
            ))}
          </Row>
        )}
      </Card>
    </div>
  )
}

export default ModuleDetail
